﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Common;
using HIWSystem.Helpers;
using HIWSystem.Models;

namespace HIWSystem.ViewModel
{
    public class ShipViewModel :ViewModelBase
    {
        //用于判断是不是第一次触发过滤，是则备份原始数据源
        private bool isFirstFilterPN = true;
        //当没有输入内容时恢复到备份的原始数据源
        ObservableCollection<PartNumberEntity> backupPNs = null;

        #region 属性
        private string sn="";
        /// <summary>
        /// 序列号
        /// </summary>
        public string SN
        {
            get { return sn; }
            set { sn = value; this.RaisePropertyChanged(() => SN); }
        }
        private bool isSnTextBoxEnabled=true;
        /// <summary>
        /// 是否启用序列号文本框
        /// </summary>
        public bool IsSnTextBoxEnabled
        {
            get { return isSnTextBoxEnabled; }
            set { isSnTextBoxEnabled = value; this.RaisePropertyChanged(() => IsSnTextBoxEnabled); }
        }
        private bool isSnTextBoxFocusable;
        /// <summary>
        /// 是否聚焦序列号文本框
        /// </summary>
        public bool IsSnTextBoxFocusable
        {
            get { return isSnTextBoxFocusable; }
            set { isSnTextBoxFocusable = value; this.RaisePropertyChanged(() => IsSnTextBoxFocusable); }
        }
        private int inputCount;
        /// <summary>
        /// 录入的数量
        /// </summary>
        public int InputCount
        {
            get { return inputCount; }
            set { inputCount = value; this.RaisePropertyChanged(() => InputCount); }
        }
        private Visibility isVisibleLoading=Visibility.Collapsed;
        /// <summary>
        /// 是否显示动画加载图表
        /// </summary>
        public Visibility IsVisibleLoading
        {
            get { return isVisibleLoading; }
            set { isVisibleLoading= value; this.RaisePropertyChanged(() => IsVisibleLoading); }
        }
        private bool isSubmitButtonEnabled=true;
        /// <summary>
        /// 是否启用提交按钮
        /// </summary>
        public bool IsSubmitButtonEnabled
        {
            get { return isSubmitButtonEnabled; }
            set { isSubmitButtonEnabled= value; this.RaisePropertyChanged(() => IsSubmitButtonEnabled); }
        }
        private ObservableCollection<string> inputSns;
        /// <summary>
        /// 已刷的序列号
        /// </summary>
        public ObservableCollection<string> InputSns
        {
            get { return inputSns; }
            set { inputSns = value; this.RaisePropertyChanged(() => InputSns); }
        }
        private ObservableCollection<TrackingCombineSnEntity> snTracking;
        /// <summary>
        /// SHIP序列号过程信息
        /// </summary>
        public ObservableCollection<TrackingCombineSnEntity> SnTracking
        {
            get { return snTracking; }
            set { snTracking = value; this.RaisePropertyChanged(() => SnTracking); }
        }
        private ObservableCollection<string> errorSns;
        /// <summary>
        /// 错误的序列号信息
        /// </summary>
        public ObservableCollection<string> ErrorSns
        {
            get { return errorSns; }
            set { errorSns = value; this.RaisePropertyChanged(() => ErrorSns); }
        }
        private ObservableCollection<PartNumberEntity> pns;
        /// <summary>
        /// 机种实体集合
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }
        private PartNumberEntity selectedPartNumber;
        /// <summary>
        /// 选择的机种实体
        /// </summary>
        public PartNumberEntity SelectedPartNumber
        {
            get { return selectedPartNumber; }
            set { selectedPartNumber = value; this.RaisePropertyChanged(() => SelectedPartNumber); }
        }
        private bool isOpenComboPNDropDown;
        /// <summary>
        /// 是否展开机种下拉框选项卡
        /// </summary>
        public bool IsOpenComboPNDropDown
        {
            get { return isOpenComboPNDropDown; }
            set { isOpenComboPNDropDown = value; this.RaisePropertyChanged(() => IsOpenComboPNDropDown); }
        }
        private string searchPNText;
        /// <summary>
        /// 机种下拉框中输入的文本内容
        /// </summary>
        public string SearchPNText
        {
            get { return searchPNText; }
            set { searchPNText = value; this.RaisePropertyChanged(() => SearchPNText); }
        }
        private string pn;
        /// <summary>
        /// 机种
        /// </summary>
        public string PN
        {
            get { return pn; }
            set { pn = value; this.RaisePropertyChanged(() => PN); }
        }
        
        private int selectIndex=0;
        /// <summary>
        /// 机种
        /// </summary>
        public int SelectIndex
        {
            get { return selectIndex; }
            set { selectIndex = value; this.RaisePropertyChanged(() => SelectIndex); }
        }
        #endregion

        #region 命令
        private RelayCommand loadedPageCmd;

        public RelayCommand LoadedPageCmd
        {
            get {

                return loadedPageCmd ?? new RelayCommand(LoadedPage);
            
            }
            set { loadedPageCmd = value; }
        }
        
        private RelayCommand submitCmd;

        public RelayCommand SubmitCmd
        {
            get
            {
                if (submitCmd == null)
                {
                    submitCmd = new RelayCommand(Submit);
                }
                return submitCmd;
            }
            set { submitCmd = value; }
        }
        private RelayCommand snKeyEnterCommand;

        public RelayCommand SNKeyEnterCommand
        {
            get
            {
                if (snKeyEnterCommand == null)
                {
                    snKeyEnterCommand = new RelayCommand(SnKeyEnterHandler);
                }
                return snKeyEnterCommand;
            }
            set { snKeyEnterCommand = value; }
        }
        private RelayCommand filterPNCmd;

        public RelayCommand FilterPNCmd
        {
            get
            {
                if (filterPNCmd == null)
                {
                    filterPNCmd = new RelayCommand(FilterPN);
                }
                return filterPNCmd;
            }
            set { filterPNCmd = value; }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadedPage()
        {
            this.IsSnTextBoxFocusable = true;
            FillPNsToComboBox();
        }
        /// <summary>
        /// 生产报告并提交出货信息到后台
        /// </summary>
        private  void Submit()
        {
            SaveShipTrackingAsync();
        }
        /// <summary>
        /// 填充机种信息到下拉列表框
        /// </summary>
        private void FillPNsToComboBox()
        {
            Task.Run(() => {
                DataTable dtPNs = new DataTable();
                dtPNs = BusinessProcess.GetPNs(EnumPNType.All);
                Application.Current.Dispatcher.BeginInvoke(new Action(() => {
                    PNs = new ObservableCollection<PartNumberEntity>();
                    for (int i = 0; i < dtPNs.Rows.Count; i++)
                    {
                        PNs.Add(new PartNumberEntity
                        {
                            PN = dtPNs.Rows[i]["PartNumber"].ToString()
                        });
                    }
                    SelectIndex = 0;
                }));
            });

        }
        /// <summary>
        /// 保存SHIP过站信息和生成测试报告
        /// </summary>
        /// <returns></returns>
        private async Task SaveShipTrackingAsync()
        {
            TrackingEntity trackingEntity = new TrackingEntity();
            await Task.Run(() =>
            {
                try
                {
                    trackingEntity.StartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    SetControlEnabledState(false);//禁用文本框和按钮防止用户再次输入
                    this.IsSnTextBoxFocusable = false;
                    this.IsVisibleLoading = Visibility.Visible;//显示加载动画
                    if (VerifyInputInfo() == false)
                        return;

                    //保存Ship信息到后台数据库中
                    //初始化实体信息
                    string retMsg = string.Empty;//返回的检测信息
                    trackingEntity.Sn = this.SN ?? "";
                    trackingEntity.Station = "SHIP";
                    trackingEntity.Result = "PASS";
                    trackingEntity.EquipmentName = Environment.MachineName;
                    trackingEntity.StopTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //站位结束时间
                    trackingEntity.Actor = LogInInfo.User;
                    DataTable dtShip = new DataTable();
                    retMsg = BusinessProcess.AddEndTracking(trackingEntity, out dtShip);
                    var arrayMsg = new string[2];
                    arrayMsg = retMsg.Split('|');
                    if (arrayMsg[0] == "OK")
                    {
                        Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            SnTracking = SnTracking ?? new ObservableCollection<TrackingCombineSnEntity>();
                            SnTracking.Add(new TrackingCombineSnEntity
                            {
                                Sn = this.SN ?? "",
                                Station = "SHIP",
                                Result = "PASS",
                                EquipmentName = Environment.MachineName,
                                Actor = LogInInfo.User,
                                CreateAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                            });
                            //根据时间进行降序排序，便于将最近一条记录显示再最上面。
                            var a = SnTracking.OrderByDescending(x => Convert.ToDateTime(x.CreateAt)).ToList();
                            SnTracking = new ObservableCollection<TrackingCombineSnEntity>();
                            for (int i = 0; i < a.Count; i++)
                            {
                                SnTracking.Add(new TrackingCombineSnEntity
                                {
                                    Sn = a[i].Sn ?? "",
                                    PN = a[i].PN ?? "",
                                    Station = a[i].Station ?? "",
                                    Result = a[i].Result ?? "",
                                    EquipmentName = a[i].EquipmentName ?? "",
                                    Actor = a[i].Actor ?? "",
                                    CreateAt = a[i].CreateAt ?? "",
                                });
                            }

                            //更新已刷数量并添加序列号和机种信息到列表中
                            this.InputCount += 1;
                            if (InputSns == null)
                                InputSns = new ObservableCollection<string>();
                            InputSns.Add(this.SN);
                            LogHelper.WriteShipLog(string.Format("序列号【{0}】出货成功", this.SN ?? ""));
                            this.SN = ""; //清空序列号信息
                        }));
                    }
                    else if (arrayMsg[0] == "NO")
                    {
                        MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                        LogHelper.WriteShipLog(string.Format("记录序列号【{0}】出货信息到数据库时发生错误【{1}】", this.SN ?? "", arrayMsg[1]));
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(ex.Message, ex);
                    LogHelper.WriteShipLog(string.Format("序列号【{0}】出货过程中发生错误【{1}】", this.SN ?? "", ex.Message));
                    MessageBox.Show(string.Format("在保存数据和生成报告过程中发生错误【{0}】!", ex.Message), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    SetControlEnabledState(true); //启用文本框和按钮
                    this.IsVisibleLoading = Visibility.Collapsed; //隐藏加载动画
                    this.IsSnTextBoxFocusable = true;
                }
            });


        }
        /// <summary>
        /// 验证输入的信息
        /// </summary>
        /// <returns></returns>
        private bool VerifyInputInfo()
        {
            string inputSn = string.Empty;
            string selectPN = string.Empty;
            string behindPN = string.Empty;//数据库中的机种信息
            string retMsg = string.Empty;//存储过程返回的信息
            inputSn = this.SN ?? "";
            //this.SN = "";
            if (inputSn == "")
            {
                MessageBox.Show("输入的序列号不能为空!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            behindPN = BusinessProcess.SnOwnerPN(inputSn);
            if (behindPN != PN)
            {
                MessageBox.Show(string.Format("输入的条码【{0}】不属于机种【{1}】.\r\n请确认输入的信息是否正确?如果正确请切换机种信息.", inputSn, PN), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            retMsg = BusinessProcess.VerifyShipWorkStation(inputSn);
            string[] arrayMsg = new string[2];
            arrayMsg = retMsg.Split('|');
            if (arrayMsg[0]=="NO")
            {
                MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            return true;
            //return arrayMsg[0] == "OK" ? true : false;
        }
        //设置控件可用状态值
        private void SetControlEnabledState(bool state)
        {
            Application.Current.Dispatcher.BeginInvoke((Action)(()=> {
                this.IsSnTextBoxEnabled = state;
                this.IsSubmitButtonEnabled = state;
            }));
        }
        /// <summary>
        /// 序列号文本框回车事件处理
        /// </summary>
        private void SnKeyEnterHandler()
        {
            Submit();
        }
        //过滤机种信息
        private void FilterPN()
        {

            IsOpenComboPNDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterPN)
            {
                backupPNs = new ObservableCollection<PartNumberEntity>();
                backupPNs = PNs;
                isFirstFilterPN = false;
            }
            if (!string.IsNullOrEmpty(SearchPNText))
            {
                IEnumerable<PartNumberEntity> partNumberEntities = PNs.Where(s => s.PN.ToUpper().Contains(SearchPNText.ToUpper()));
                PNs = new ObservableCollection<PartNumberEntity>();
                foreach (var p in partNumberEntities)
                {
                    PNs.Add(p);
                }
            }
            else
            {
                PNs = backupPNs;
            }

        }

        #endregion

    }
}
